package com.ciwong.epaper.modules.epaper.adapter;

import android.content.Context;
import android.graphics.Color;
import android.net.TrafficStats;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.me.ui.LoadingFileActivity;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.util.download.ProgressCircle;
import com.ciwong.libs.utils.CWLog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * CatalogActivity相关adapter
 * <p/>
 * Created by res-yinxue on 2016/7/8.
 */
public class CatalogAdapter2 extends BaseExpandableListAdapter {

    //public static final int ItemHeight = 0;

    /**
     * 数据集合
     */
    List<CatalogueInfo> catalogueInfos;

    List<DownLoadInfo> mDownLoadInfoList;


    /**
     * 上下文
     */
    Context mContext;

    private LayoutInflater mInflater;

    private int LIST_TYPE;

    private boolean isHideDownloadBtn = false;// 是否隐藏下载按钮

    private Handler mHandler = new Handler();

    //获取通过Mobile连接收到的字节总数
    private long total_data = TrafficStats.getTotalRxBytes();

    private DownLoadInfo downLoadInfo;

    /**
     * 构造器
     *
     * @return
     */
    public CatalogAdapter2(Context context,
                           boolean isHideDownloadBtn,
                           int type) {
        this.mContext = context;
        this.catalogueInfos = new ArrayList<CatalogueInfo>();
        this.isHideDownloadBtn = isHideDownloadBtn;
        this.LIST_TYPE = type;
        mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getGroupCount() {
        return catalogueInfos == null ? 0 : catalogueInfos.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return catalogueInfos == null ? 0 : catalogueInfos.get(groupPosition).getChildren().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return catalogueInfos == null || catalogueInfos.isEmpty() ? null : catalogueInfos.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return catalogueInfos == null || catalogueInfos.isEmpty() ? null : catalogueInfos.get(groupPosition).getChildren().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.adapter_threedirectory_item, null);
            holder.nameTV = (TextView) convertView.findViewById(R.id.name_tv);
            holder.progressCircle = (ProgressCircle) convertView
                    .findViewById(R.id.directory_item_min_pb);
            holder.horPb = (ProgressBar) convertView.findViewById(R.id.directory_item_hor_pb);
            holder.sizeTV = (TextView) convertView.findViewById(R.id.size_tv);
            holder.speedTV = (TextView) convertView.findViewById(R.id.down_speed__tv);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        String name = catalogueInfos.get(groupPosition).getName();
        holder.nameTV.setText(name);
        holder.nameTV.setGravity(Gravity.CENTER_VERTICAL);
        //setParams(convertView);
        boolean hasNoChild = catalogueInfos.get(groupPosition).getChildren().size() == 0 ? true : false;

        if (hasNoChild) {
            holder.progressCircle.setVisibility(View.VISIBLE);
            holder.horPb.setVisibility(View.VISIBLE);
            CatalogueInfo info = (CatalogueInfo) getGroup(groupPosition);
            downLoadInfo = getDownLoadInfo(info);
            if (downLoadInfo != null) {
                dealCircleProgress(downLoadInfo, holder.horPb, holder.progressCircle, holder.sizeTV, holder.speedTV);
            }
            if (isHideDownloadBtn) {
                convertView.setBackgroundColor(Color.WHITE);
            }
        }


        return convertView;
    }


    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        CatalogueInfo cInfo = (CatalogueInfo) getGroup(groupPosition);
        if (cInfo.getChildren().size() == 0 || null == cInfo.getChildren()) {
            return null;
        }
        ViewChildHolder childHolder;
        if (convertView == null) {
            childHolder = new ViewChildHolder();
            convertView = mInflater.inflate(R.layout.adapter_threedirectory_item, null);
            childHolder.nameTV = (TextView) convertView.findViewById(R.id.name_tv);
            childHolder.progressCircle = (ProgressCircle) convertView
                    .findViewById(R.id.directory_item_min_pb);
            childHolder.horPb = (ProgressBar) convertView.findViewById(R.id.directory_item_hor_pb);
            childHolder.sizeTV = (TextView) convertView.findViewById(R.id.size_tv);
            childHolder.speedTV = (TextView) convertView.findViewById(R.id.down_speed__tv);
            convertView.setTag(childHolder);
        } else {
            childHolder = (ViewChildHolder) convertView.getTag();
        }
        //第三层级显示两个控件
        childHolder.progressCircle.setVisibility(View.VISIBLE);
        childHolder.horPb.setVisibility(View.VISIBLE);

        String name = catalogueInfos.get(groupPosition).getChildren().get(childPosition).getName();
        childHolder.nameTV.setGravity(Gravity.CENTER_VERTICAL);
        childHolder.nameTV.setText(name);
        childHolder.nameTV.setPadding(25, 0, 0, 0);
       // setParams(convertView);

        CatalogueInfo info = (CatalogueInfo) getChild(groupPosition, childPosition);
        downLoadInfo = getDownLoadInfo(info);

        if (downLoadInfo != null) {
            dealCircleProgress(downLoadInfo, childHolder.horPb, childHolder.progressCircle, childHolder.sizeTV, childHolder.speedTV);
        }


        if (isHideDownloadBtn) {
            convertView.setBackgroundColor(Color.WHITE);
        }


        return convertView;
    }

    private DownLoadInfo getDownLoadInfo(CatalogueInfo curInfo) {
        DownLoadInfo downLoadInfo = null;
        if (mDownLoadInfoList != null && mDownLoadInfoList.size() > 0) {
            for (int i = 0; i < mDownLoadInfoList.size(); i++) {
                if (mDownLoadInfoList.get(i).getChapterId().equals(curInfo.getId())) {
                    downLoadInfo = mDownLoadInfoList.get(i);
                    break;
                }
            }
        }
        return downLoadInfo;
    }

    public void setParams(View view) {
        int itemHeight = (int) mContext.getResources().getDimension(R.dimen.book_list_height);
        RelativeLayout relativeLayout = (RelativeLayout) view;
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, itemHeight);
        relativeLayout.setLayoutParams(lp);
        relativeLayout.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    private void dealCircleProgress(final DownLoadInfo info, final ProgressBar horPb,
                                    final ProgressCircle progressCircle,
                                    final TextView sizeText,
                                    final TextView speedText) {
        if (isHideDownloadBtn || (LIST_TYPE == CatalogueInfo.LIST_COMPLETED
                && info.getStatus() == DownloadStatus.STATUS_COMPLETED)) {
            CWLog.e("TAT", "C2 ====== DownloadStatus.XXXXXXXXXXXXXXXXXXXXXX");
            progressCircle.setVisibility(View.GONE);
            sizeText.setVisibility(View.GONE);
            speedText.setVisibility(View.GONE);
            return;
        }
        progressCircle.setIsError(false);
        switch (info.getStatus()) {
            case DownloadStatus.STATUS_NORMAL:
                CWLog.e("TAT", "C2 ====== DownloadStatus.STATUS_NORMAL 5");
                horPb.setProgress(0);
                progressCircle.updateDownloadProgress(0);
                progressCircle.setIsError(TextUtils.isEmpty(info.getUrl()));
                progressCircle.initToNormal();
                break;
            case DownloadStatus.STATUS_LOADING:
                CWLog.e("TAT", "C2 ====== DownloadStatus.STATUS_LOADING");
                horPb.setProgress(0);
                progressCircle.initToLoading();
                //文件大小
                sizeText.setVisibility(View.VISIBLE);
                speedText.setVisibility(View.VISIBLE);
                sizeText.setText(info.getSize() + " MB");
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                CWLog.e("TAT", "C2 ====== DownloadStatus.STATUS_DOWNLOADING");
                DownLoadInfo currentInfo = DownLoad.getInstance()
                        .getCurrentBean(info);
                if (currentInfo != null) {
                    info.setProgress(currentInfo.getProgress());
                }
                if(sizeText.getVisibility()==View.GONE||sizeText.getVisibility()==View.INVISIBLE){
                    CWLog.e("TAT","112233");
                }else{
                    CWLog.e("TAT","View.VISIBLE size文件大小："+info.getSize());
                }
                //实时下载的网速
                long downSpeed = getNetSpeed();
                speedText.setText(downSpeed / 1024 + " kb/s");

                horPb.setProgress(info.getProgress());
                progressCircle
                        .updateDownloadProgress(info.getProgress() / 100f);
                break;
            case DownloadStatus.STATUS_COMPLETED:
                CWLog.e("TAT", "C2 ====== DownloadStatus.STATUS_COMPLETED !!!!!!!!!");
                if (LIST_TYPE == CatalogueInfo.LIST_ALL) {
                    String packageDir = ESystem.getPackagesCatalogue(
                            info.getBookId(), info.getChapterId());
                    Log.i("se7en", "LIST_ALL" + packageDir);
                    if (new File(packageDir).exists()) {
                        horPb.setProgress(0);
                        progressCircle.initToCompleted();
                    } else {
                        info.setProgress(0);
//                        DownLoad.getInstance().stopTask(info);
                    }
                    speedText.setVisibility(View.GONE);
                    sizeText.setVisibility(View.GONE);
                } else if (LIST_TYPE == CatalogueInfo.LIST_DOWNLOADING) {
                    CWLog.e("TAT", "C2 ====== DownloadStatus.LIST_DOWNLOADING");
                    String packageDir = ESystem.getPackagesCatalogue(
                            info.getBookId(), info.getChapterId());
                    Log.i("se7en", "LIST_DOWNLOADING" + packageDir);
                    if (new File(packageDir).exists()) {
                        catalogueInfos.remove(info);
                        if (mContext instanceof LoadingFileActivity) {
                            ((LoadingFileActivity) mContext).showLlEmpty();
                        }
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                notifyDataSetChanged();
                            }
                        }, 10);
                    }
//                    else {
//                        DownLoad.getInstance().stopTask(info);
//                    }
                }
                break;
            case DownloadStatus.STATUS_PAUSE:
                CWLog.e("TAT", "C2 ====== DownloadStatus.STATUS_PAUSE");
                horPb.setProgress(info.getProgress());
                progressCircle.initToPause();
                break;
            case DownloadStatus.STATUS_FAILED:
            case DownloadStatus.STATUS_FAILED_SDISFULL:
            case DownloadStatus.STATUS_FAILED_UNZIP:
                CWLog.e("TAT", "C2 ====== DownloadStatus.STATUS_FAILED");
                horPb.setProgress(0);
                Log.i("se7en", this.getClass().getName()
                        + "DownloadStatus.STATU_FAILED");
                progressCircle.initToFAILED();
                break;
            case DownloadStatus.STATUS_UPZIPING:
                CWLog.e("TAT", "C2 ====== DownloadStatus.STATUS_UPZIPING");
                horPb.setProgress(100);
                progressCircle.initToLoading();
                break;
        }
    }


    private static class ViewHolder {
        TextView nameTV, sizeTV, speedTV;

        ProgressBar horPb;

        ProgressCircle progressCircle;

    }

    private static class ViewChildHolder {
        TextView nameTV, sizeTV, speedTV;

        ProgressBar horPb;

        ProgressCircle progressCircle;
    }

    /**
     * 得到当前网速
     *
     * @return
     */
    private long getNetSpeed() {
        long traffic_data = TrafficStats.getTotalRxBytes() - total_data;
        total_data = TrafficStats.getTotalRxBytes();
        return traffic_data;
    }


    /**
     * 获取数据
     *
     * @return
     */
    public List<CatalogueInfo> getCatalogueInfo() {
        return catalogueInfos;
    }

    /**
     * 更新数据
     *
     * @param catalogueInfos
     */
    public void updateCatalogueInfo(List<CatalogueInfo> catalogueInfos) {
        //this.catalogueInfos.clear();
        if (this.catalogueInfos == null) {
            this.catalogueInfos = new ArrayList<CatalogueInfo>();
        }
        if (catalogueInfos != null) {
            for (CatalogueInfo info : catalogueInfos) {
                this.catalogueInfos.add(info);
            }
            notifyDataSetChanged();
        }

    }

    /**
     * 添加数据
     */
    public void addAll(List<CatalogueInfo> catalogueInfos) {
        if (this.catalogueInfos == null) {
            this.catalogueInfos = new ArrayList<CatalogueInfo>();
        }
        if (catalogueInfos != null) {
            this.catalogueInfos = catalogueInfos;
            notifyDataSetChanged();
        }

    }

    /**
     * 移除数据
     */
    public void removeAll() {
        if (catalogueInfos != null) {
            catalogueInfos.clear();
            notifyDataSetChanged();
        }
    }

    public void setDownLoadInfoList(List<DownLoadInfo> downLoadInfoList) {
        if (null != downLoadInfoList && downLoadInfoList.size() > 0) {
            mDownLoadInfoList = downLoadInfoList;
        }

    }

}
